/*
 * Copyright (c) 2024 Cshoo Org. All Rights Reserved.
 *
 * author:杨翼
 * date: 2024年5月13日
 * description:word list组件html渲染后端java model
 */

package org.cshoo.presentation.mwd.model;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

import java.util.Iterator;
import java.util.Objects;

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
@Slf4j
@Setter
public class WordsList {

    @Self
    private Resource resource;

    @ValueMapValue
    private String title;

    @ValueMapValue
    private String description;

    /**
     * words list组件传出json类型的数据，供前端vue全局使用
     *
     * @return 组件配置的数据
     */
    public String getJsonData() {
        JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("title", title);
        jsonObject.addProperty("description", description);

        JsonArray jsonArray = new JsonArray();
        log.info("resource:{}", resource);
        Resource wordsResource = resource.getChild("words");
        if (Objects.nonNull(wordsResource)) {
            Iterator<Resource> wordIterator = wordsResource.listChildren();
            Gson gson = new Gson();
            while (wordIterator.hasNext()) {
                Resource wordResource = wordIterator.next();
                log.info("wordResource:{}", wordResource);
                ValueMap valueMap = wordResource.getValueMap();
                Word word = new Word();
                word.setSpell(valueMap.get("spell", String.class));
                word.setExplanation(valueMap.get("explanation", String.class));
                log.info("word:{}", word);
                jsonArray.add(gson.toJsonTree(word, Word.class));
            }
        }
        jsonObject.add("words", jsonArray);

        String result = jsonObject.toString();
        log.info("result:{}", result);

        return result;
    }
}
